package cn.org.wangchangjiu.sqltomongo.core.common;

import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.UUID;

@Data
public class MongoIndex {
    /**
     * 要加索引的字段，联合索引则按顺序
     */
    List<String> fields;

    /**
     * 是否为唯一索引
     */
    boolean isUnique;

    public String toJson(String collectionName) {
        return "{"+getFieldsJson()+"},{unique:"+isUnique+",\"name\":\""+ getIndexName(collectionName) +"\"}";
    }

    private String getIndexName(String collectionName) {
        if (!CollectionUtils.isEmpty(fields)) {
            StringBuilder sb = new StringBuilder(collectionName);
            for (String field : fields) {
                sb.append("_").append(field);
            }
            return sb.toString();
        }
        return "";
    }

    private String getFieldsJson() {
        StringBuilder result = new StringBuilder();
        for (String field : fields) {
            result.append(",").append("\"").append(field).append("\"").append(":1");
        }
        return result.substring(1);
    }
}
